package phone.qyg.com.qyg.activity;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.app.base.tool.BaseActivity;
import com.app.config.ApplicationConfig;
import com.app.utils.SystemPrintl;
import com.app.view.view.SonicRuntimeImpl;
import com.app.view.view.SonicSessionClientImpl;
import com.tencent.sonic.sdk.SonicConfig;
import com.tencent.sonic.sdk.SonicEngine;
import com.tencent.sonic.sdk.SonicSession;
import com.tencent.sonic.sdk.SonicSessionConfig;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import phone.qyg.com.qyg.R;
import phone.qyg.com.qyg.model.About;
import phone.qyg.com.qyg.model.ActivityDetail;
import phone.qyg.com.qyg.model.Base;
import phone.qyg.com.qyg.model.Content;
import phone.qyg.com.qyg.model.Roll;
import phone.qyg.com.qyg.model.VenueDetail;

/**
 * 作者：lblbh on 2017/12/6 17:24
 * 邮箱：lanbuhan@163.com
 * 功能：html
 */
@ContentView(R.layout.html_layout)
public class HtmlActivity extends BaseActivity {

    @ViewInject(R.id.back)
    TextView back;

    @ViewInject(R.id.web_view)
    WebView web_view;

    String abstractStr;

    String fixImgUrl;

    String title;

    String url;

    ShareAction mShareAction;

    int aboutApp;

    SonicSession sonicSession;

    SonicSessionClientImpl sonicSessionClient;

    boolean isCloseImg; //true 关闭点击图片
    @Override
    public void initSucessView() {
        Object obj = getTransModels();
//        if (obj instanceof Base){
//            Base base = (Base) obj;
//            url = base.more;
//            title = base.title;
//        }

        if (obj instanceof VenueDetail) {
            VenueDetail venueDetail = (VenueDetail) obj;
            url = venueDetail.more;
            title = venueDetail.title;
        }else if(obj instanceof ActivityDetail){
            ActivityDetail actDetail = (ActivityDetail) obj;
            url = (actDetail.isHtml == 0)?actDetail.more : actDetail.actDeclare;
            title = actDetail.title;
        }else if(obj instanceof Content){
            Content content = (Content) obj;
            url = content.more;
            title = content.title;
        } else if (obj instanceof Roll) {
            Roll roll = (Roll) obj;
            url = roll.sourceUrl;
            title = roll.title;
        }else if(obj instanceof About){
            About about = (About) obj;
            url = about.url;
            title = about.title;
            isCloseImg = true;
        }else if(obj instanceof Base){
            Base base = (Base) obj;
            url = base.url;
            title = base.title;
        }

        if(!isRequestStr(url))
            return;

        // step 1: Initialize sonic engine if necessary, or maybe u can do this when application created
        if (!SonicEngine.isGetInstanceAllowed()) {
            SonicEngine.createInstance(new SonicRuntimeImpl(getApplication()), new SonicConfig.Builder().build());
        }

        // step 2: Create SonicSession
        sonicSession = SonicEngine.getInstance().createSession(url,  new SonicSessionConfig.Builder().build());
        if (null != sonicSession) {
            sonicSession.bindClient(sonicSessionClient = new SonicSessionClientImpl());
        } else {
            throw new UnknownError("create session fail!");
        }
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        if (!isRequestStr(url)) return;

        back.setText(setAttributeText(title));
        initWebView();
    }

    private void initWebView() {
        //初始化布局
        WebSettings settings = web_view.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setSupportZoom(false);// 允许放大缩小
        settings.setBuiltInZoomControls(false);// 显示放大缩小按钮
        settings.setDisplayZoomControls(false);// api 11以上
        settings.setSupportMultipleWindows(true);
        settings.setGeolocationEnabled(true);// 启用地理定位
        settings.setTextZoom(100);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        web_view.setWebChromeClient(new WebChromeClient());
        web_view.setHorizontalScrollBarEnabled(false);
        web_view.setBackgroundColor(Color.TRANSPARENT); // 设置背景色
        //载入js
        web_view.addJavascriptInterface(new JavascriptInterface(this), "imagelistner");


        if (sonicSessionClient != null) {
            sonicSessionClient.bindWebView(web_view);
            sonicSessionClient.clientReady();
        } else { // default mode
            web_view.loadUrl(url);
        }
//        web_view.loadUrl(url);

        //http://wx.nmge-sports.com/wechatnews/1754/sportsnewsdetail.shtml
        web_view.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //该方法在Build.VERSION_CODES.LOLLIPOP以前有效，从Build.VERSION_CODES.LOLLIPOP起，建议使用shouldOverrideUrlLoading(WebView, WebResourceRequest)} instead
                //返回false，意味着请求过程里，不管有多少次的跳转请求（即新的请求地址），均交给webView自己处理，这也是此方法的默认处理
                //返回true，说明你自己想根据url，做新的跳转，比如在判断url符合条件的情况下，我想让webView加载http://ask.csdn.net/questions/178242
                if(url.endsWith(".docx") ){
                    StringBuffer buffer = new StringBuffer(ApplicationConfig.APP_OFFICE_HTMl);
//                    StringBuffer buffer = new StringBuffer("https://view.officeapps.live.com/op/view.aspx?src=http://img.pmphmooc.com/andriod/test.xls");
                    buffer.append(url);
                    Uri uri = Uri.parse(buffer.toString());
                    Intent intent = new Intent(Intent.ACTION_VIEW,uri);
                    startActivity(intent);
                }else{
                    view.loadUrl(url);
                }
//                url = "https://view.officeapps.live.com/op/view.aspx?src=http%3A%2F%2Fimg.nmge-sports.com%3A8010%2Fatta%2Fdata%2Fcontent%2Fcontent%2Fcontent%2F2017%2F09%2F20%2F6dcea3f7-f4ff-4533-8620-f021799ab5ca.docx";
////                view.loadUrl(url);
//                Uri uri = Uri.parse(url);
//                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
//                startActivity(intent);
                return true;
            }

            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                //返回false，意味着请求过程里，不管有多少次的跳转请求（即新的请求地址），均交给webView自己处理，这也是此方法的默认处理
                //返回true，说明你自己想根据url，做新的跳转，比如在判断url符合条件的情况下，我想让webView加载http://ask.csdn.net/questions/178242
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    String tempURL = request.getUrl().toString();
                    if(tempURL.endsWith(".docx") ){
                        StringBuffer buffer = new StringBuffer(ApplicationConfig.APP_OFFICE_HTMl);
                        buffer.append(tempURL);
                        Uri uri = Uri.parse(buffer.toString());
                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                        startActivity(intent);
                    }else{
                        view.loadUrl(tempURL);
                    }
                    return true;
                }

                return false;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                //网页页面加载完毕
                if(!isCloseImg){
                    //图片点击注入
                    addImageClickListner();
                }


                if (sonicSession != null) {
                    sonicSession.getSessionClient().pageFinish(url);
                }
            }

            //下面的方法是Tencent - sonic
            @TargetApi(21)
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                return shouldInterceptRequest(view, request.getUrl().toString());
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                if (sonicSession != null) {
                    //step 6: Call sessionClient.requestResource when host allow the application
                    // to return the local data .
                    return (WebResourceResponse) sonicSession.getSessionClient().requestResource(url);
                }
                return null;
            }
        });

//        web_view.setDownloadListener(new MyWebViewDownLoadListener());
    }

//    private class MyWebViewDownLoadListener implements DownloadListener {
//
//        @Override
//        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,long contentLength) {
//            Uri uri = Uri.parse(url);
//            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
//            startActivity(intent);
//        }
//
//    }

    // 注入js函数监听
    private void addImageClickListner() {
        //http://wx.test.nmge-sports.com/img/back_top.png
        ////time_03.jpg  /bi_03.jpg
        // 这段js函数的功能就是，遍历所有的img几点，并添加onclick函数，函数的功能是在图片点击的时候调用本地java接口并传递url过去
        web_view.loadUrl("javascript:(function(){" +
                "var objs = document.getElementsByTagName(\"img\"); " +
                "for(var i=0;i<objs.length;i++)  " +
                "{"
                + "var imgValue = objs[i].src;"
                + "if(imgValue.endsWith(\"back_top.png\") || " +
                "       imgValue.endsWith(\"time_03.jpg\") || " +
                "       imgValue.endsWith(\"bi_03.jpg\"))"
                + "{"
                + "continue;"
                + "}"
                + "    objs[i].onclick=function()  " +
                "    {  "
                + "        window.imagelistner.openImage(this.src);  " +
                "    }  " +
                "}" +
                "})()");


        /**
         web_view.loadUrl("javascript:(function(){" +
         "var objs = document.getElementsByTagName(\"img\"); " +
         "for(var i=0;i<objs.length;i++)  " +
         "{"
         + "    objs[i].onclick=function()  " +
         "    {  "
         + "        window.imagelistner.openImage(this.src);  " +
         "    }  " +
         "}" +
         "})()");
         */

    }

    // js通信接口
    public class JavascriptInterface {

        private Context context;


        public JavascriptInterface(Context context) {
            this.context = context;
        }

        @android.webkit.JavascriptInterface
        public void openImage(String img) {
            SystemPrintl.systemPrintl("图片地址是---->>>"+img);
            if(!isRequestStr(img))return;
            Intent intent = new Intent();
            intent.putExtra("image", img);
            intent.setClass(context, ShowWebImageActivity.class);
            startActivity(intent);
        }
    }


    @Event(value = {R.id.back})
    private void viewOnClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                if (web_view.canGoBack())
                    web_view.goBack();
                else
                    this.finish();
                break;
        }
    }

    @Override
    public void initViewHandler() {
    }

    //重写Activity的onKeyDown事件，判断当用户按下“返回”按钮，webview返回上一页
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && web_view.canGoBack()) {
            web_view.goBack();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 屏幕横竖屏切换时避免出现window leak的问题
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mShareAction.close();
    }


    /**
     * 主要是把webview所持用的资源销毁，
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(null != web_view){
            web_view.setWebChromeClient(null);
            web_view.setWebViewClient(null);
            web_view.destroy();
            web_view = null;
        }

        if (null != sonicSession) {
            sonicSession.destroy();
            sonicSession = null;
        }
    }
}
